package cn.xyinping.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 27266
 * @desrciption 自定义filter
 * @date 2021/11/19
 */
// 把这个类交给spring管理
@Component
public class CheckLoginFilter extends ZuulFilter {
    private static final Logger log = LoggerFactory.getLogger(CheckLoginFilter.class);
    // 执行顺序
    private static final int ORDER = 1;

    // filter(过滤器)类型：“pre前置”
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    // 执行顺序
    @Override
    public int filterOrder() {
        return ORDER;
    }
    // 返回值结果决定要不要执行run方法
    @Override
    public boolean shouldFilter() {
        // 1. 获取request对象，获取请求中的url
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String requestURI = request.getRequestURI();
        log.info("请求地址："+requestURI);
        // 2. 判断是否包含在static/** /login /register
        if(requestURI.endsWith("/login")||requestURI.endsWith("/register")||requestURI.contains("/static/")){
            return false;
        }
        // 要做登录检查返回true
        return true;
    }
    //核心业务方法 ： 登录检查 ， 如果请求头中有token，就是登录成功
    @Override
    public Object run() throws ZuulException {
        // 1. 获取请求对象
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        // 2. 拿到请求头中token
        String token = request.getHeader("token");
        // 3. 判断token是否为空，为空没登陆
        if(StringUtils.isEmpty(token)){
            // 返回一个请登录的提示
            HttpServletResponse response = context.getResponse(); // 获取响应
            try {
                // 解决乱码
                response.setContentType("aplication/json;charset=utf-8");
                response.getWriter().write("请登录");
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 阻止继续往后执行
            context.setSendZuulResponse(false);
        }
        // 如果不为空就放行
        return null;
    }
}
